/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.security.servlet;

import java.util.function.Supplier;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 基于 {@link ApplicationContext} 的 {@link RequestMatcher} 实现。
 * 可以直接使用 {@link ApplicationContext}，获取已有的 Bean，
 * 或通过 {@link AutowireCapableBeanFactory#createBean(Class, int, boolean)}
 * 创建一个新的并自动注入的 Bean。
 *
 * @param <C> 实际匹配方法所需使用的上下文类型。可以是 {@link ApplicationContext}，
 *            也可以是 {@link ApplicationContext#getBean(Class)} 返回的已有 Bean 类型。
 * @author Phillip Webb
 * @since 2.0.0
 */
public abstract class ApplicationContextRequestMatcher<C> implements RequestMatcher {

	private final Class<? extends C> contextClass;

	private volatile boolean initialized;

	private final Object initializeLock = new Object();

	public ApplicationContextRequestMatcher(Class<? extends C> contextClass) {
		Assert.notNull(contextClass, "Context class must not be null");
		this.contextClass = contextClass;
	}

	@Override
	public final boolean matches(HttpServletRequest request) {
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(request.getServletContext());
		if (ignoreApplicationContext(webApplicationContext)) {
			return false;
		}
		Supplier<C> context = () -> getContext(webApplicationContext);
		if (!this.initialized) {
			synchronized (this.initializeLock) {
				if (!this.initialized) {
					initialized(context);
					this.initialized = true;
				}
			}
		}
		return matches(request, context);
	}

	@SuppressWarnings("unchecked")
	private C getContext(WebApplicationContext webApplicationContext) {
		if (this.contextClass.isInstance(webApplicationContext)) {
			return (C) webApplicationContext;
		}
		return webApplicationContext.getBean(this.contextClass);
	}

	/**
	 * 判断是否应该忽略该 {@link WebApplicationContext}，不用于匹配。
	 * 如果返回 {@code true}，则不会使用该上下文，{@link #matches(HttpServletRequest)} 方法将返回 {@code false}。
	 * @param webApplicationContext 待判断的 Web 应用上下文
	 * @return 是否忽略该应用上下文
	 * @since 2.1.8
	 */
	protected boolean ignoreApplicationContext(WebApplicationContext webApplicationContext) {
		return false;
	}

	/**
	 * 子类可以实现此方法以在匹配器首次调用时初始化相关内容。
	 * 此方法只会被调用一次，且仅当 {@link #ignoreApplicationContext(WebApplicationContext)} 返回 {@code false} 时调用。
	 * 注意，传入的上下文是基于传给匹配器的 <strong>第一次</strong> 请求。
	 * @param context 已初始化上下文的提供者（可能会抛出异常）
	 * @see #ignoreApplicationContext(WebApplicationContext)
	 */
	protected void initialized(Supplier<C> context) {
	}

	/**
	 * 判断策略实现的规则是否匹配给定请求。
	 * @param request 源请求
	 * @param context 已初始化上下文的提供者（可能会抛出异常）
	 * @return 是否匹配
	 */
	protected abstract boolean matches(HttpServletRequest request, Supplier<C> context);

}
